/*
 * Copyright (C) 2011-2019 ShenZhen iBOXCHAIN Information Technology Co.,Ltd.
 *
 * All right reserved.
 *
 * This software is the confidential and proprietary
 * information of iBOXCHAIN Company of China.
 * ("Confidential Information"). You shall not disclose
 * such Confidential Information and shall use it only
 * in accordance with the terms of the contract agreement
 * you entered into with iBOXCHAIN inc.
 */
package ccnu.agile.enums;

import ccnu.agile.bean.exception.CAPDException;
import ccnu.agile.constant.System;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 日期格式转换
 *
 * @AUTHOR Jream.Y
 * @DATE 2021-06-04
 */
public enum DatePattern {

    /**
     * yyyy-MM-dd
     */
    Y_M_D(System.Pattern.Y_M_D),
    /**
     * yyyy-MM-dd HH:mm:ss
     */
    Y_M_D_H_M_S(System.Pattern.Y_M_D_H_M_S),
    /**
     * yyyyMMddHHmmss
     */
    YMDHMS(System.Pattern.YMDHMS);

    private String format;

    private final static Logger LOGGER = LoggerFactory.getLogger(DatePattern.class);

    DatePattern(String format) {
        this.format = format;
    }

    public String format(Date date) {
        return date == null ? null : dateFormat().format(date);
    }

    public String now() {
        return format(new Date());
    }

    public Date parse(String dateStr) {
        try {
            return StringUtils.isEmpty(dateStr) ? null : dateFormat().parse(dateStr);
        } catch (ParseException e) {
            LOGGER.error("parse error: dateStr={}, format={}", dateStr, format);
            throw new CAPDException(PrivError.DATE_FORMAT_FAIL);
        }
    }

    private SimpleDateFormat dateFormat() {
        return new SimpleDateFormat(format);
    }
}
